package juc;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <pre>类名: RateLimiterTest</pre>
 * <pre>描述: guava RateLimiter示例</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/11/2 8:31</pre>
 * <pre>作者: chenwb</pre>
 */
public class RateLimiterTest {

	//限流器流速：2个请求/秒
	static RateLimiter limiter = RateLimiter.create(2.0);
	//执行任务的线程池
	static ExecutorService es = Executors.newFixedThreadPool(1);

	private static long prev;

	public static void main(String[] args) {
		//记录上一次执行时间
		prev =System.nanoTime();
		//测试执行20次
		for(int i = 0;i<20;i++){
			//限流器限流
			limiter.acquire();
			//提交任务异步执行
			es.execute(() -> {
				long cur = System.nanoTime();
				//打印时间间隔：毫秒
				System.out.println(
						(cur - prev) / 1000_000);
				prev = cur;
			});
		}
	}

}
